<template>
<view class="container">
		<!-- 顶部开关 -->
		<view class="topButtonSwitch" @click="chooseBluetoothMenu">
			<view class="topswitch" v-if="switchStatus == 0">
				<image src="/static/icon/switchClose.png" mode=""></image>
			</view>
			<view class="topswitch" v-else>
				<image src="/static/icon/switchOpen.png" mode=""></image>
			</view>
		</view>
		
		<!-- 蓝牙区域 -->
		<view class="maskLayer" v-if="bluetoothMenu">
			<uni-collapse>
				<!-- 主操作按钮 -->
				<view class="action-buttons">
					<button class="btn bluetooth-btn" @click="toggleBluetooth">
						{{ bluetooth === 1 ? '打开蓝牙' : '关闭蓝牙' }}
					</button>
					<button class="btn search-btn" @click="openBluetoothAdapter">搜索设备</button>
					<button class="btn shut-btn" @click="chooseBluetoothMenu">关闭界面</button>
				</view>
				<!-- 已配对设备区域 -->
				<view class="paired-section">
					<view class="section-title">已配对设备</view>
					<scroll-view class="paired-list" scroll-y>
						<view v-for="(item,index) in pairedList" :key="index" class="paired-item"
							@click="setSelectedPaired(item)">
							<view class="device-info">
								<text>{{item.name || item.address}}</text>
								<text class="selected-tag" v-if="item.isSelected==1">&nbsp;&nbsp;已连接</text>
							</view>
							<view class="delete-btn" @click.stop="removePaire(index)">删除设备</view>
						</view>
					</scroll-view>
				</view>

				<!-- 未配对设备区域 -->
				<view class="unpaired-section">
					<view class="section-title">
						<view class="tip-text">说明：如果反复操作连不到蓝牙，请退出重新登录。</view>
						<view>未配对设备</view>
					</view>
					<scroll-view class="unpaired-list" scroll-y>
						<view v-for="(item,index) in unpairedList" :key="index" class="unpaired-item"
							@click="createBLEConnection(item.address)">
							{{item.name || item.address}}
						</view>
					</scroll-view>
				</view>
			</uni-collapse>
		</view>

		<!-- 音量控制 -->
		<view class="volumeNavBar">
			<view class="">
				<image src="/static/icon/volume+.png"></image>
			</view>
			<view class="">
				<view class="">
					<image src="/static/icon/volumex.png"></image>
				</view>
			</view>
			<view class="">
				<view class="">
					<image src="/static/icon/volume-.png"></image>
				</view>
			</view>
		</view>

		<!-- 方向控制 -->
		<!-- 圆形方向控制 -->
		<view class="directionControlBox">
			<!-- 圆形方向控制 -->
			<view class="direction-circle">
				<!-- 上方向 -->
				<view class="direction-btn direction-up">
					<uni-icons type="top" size="34" color="#ffffff" @click="sendDataToDevice(directives[3].text)"></uni-icons>
				</view>

				<!-- 下方向 -->
				<view class="direction-btn direction-down">
					<uni-icons type="bottom" size="34" color="#ffffff" @click="sendDataToDevice(directives[4].text)"></uni-icons>
				</view>

				<!-- 左方向 -->
				<view class="direction-btn direction-left">
					<uni-icons type="left" size="34" color="#ffffff" @click="sendDataToDevice(directives[5].text)"></uni-icons>
				</view>

				<!-- 右方向 -->
				<view class="direction-btn direction-right">
					<uni-icons type="right" size="34" color="#ffffff" @click="sendDataToDevice(directives[6].text)"></uni-icons>
				</view>

				<!-- 中间OK按钮 -->
				<view class="ok-btn" @click="sendDataToDevice(directives[1].text)">
					<text class="ok-text">OK</text>
				</view>
			</view>
		</view>
		<!-- 小控制按钮 -->
		<view class="bottonNav">
		    <!-- 卧倒 -->
		    <view class="minBut" bindtap="onActionTap" data-action="lieDown" @click="sendDataToDevice(directives[0].text)">
		        <image src="/static/icon/gegDown.png" mode="aspectFit"></image>
		    </view>
		    <!-- 蹲下 -->
		    <view class="minBut" bindtap="onActionTap" data-action="squat" @click="sendDataToDevice(directives[2].text)">
		        <image src="/static/icon/squatDown.png" mode="aspectFit"></image>
		    </view>
		    <!-- 伸左手 -->
		    <view class="minBut" bindtap="onActionTap" data-action="leftHand" @click="sendDataToDevice(directives[9].text)">
		        <image src="/static/icon/leftHand.png" mode="aspectFit"></image>
		    </view>
		    <!-- 伸右手 -->
		    <view class="minBut" bindtap="onActionTap" data-action="rightHand" @click="sendDataToDevice(directives[8].text)">
		        <image src="/static/icon/rightHand.png" mode="aspectFit"></image>
		    </view>
		</view>
		
		<view class="bottonNav">
		    <!-- 欢快 -->
		    <view class="minBut" bindtap="onActionTap" data-action="swing" @click="sendDataToDevice(directives[7].text)">
		        <image src="/static/icon/swing.png" mode="aspectFit"></image>
		    </view>
		    <!-- 挥左手 -->
		    <view class="minBut" bindtap="onActionTap" data-action="waveLeft" @click="sendDataToDevice(directives[10].text)">
		        <image src="/static/icon/waveLift.png" mode="aspectFit"></image>
		    </view>
		    <!-- 挥右手 -->
		    <view class="minBut" bindtap="onActionTap" data-action="waveRight" @click="sendDataToDevice(directives[11].text)">
		        <image src="/static/icon/waveRight.png" mode="aspectFit"></image>
		    </view>
		    <!-- ？？？ -->
		    <view class="minBut placeholder" @click="sendDataToDevice(directives[12].text)">
		        <image src="" mode=""></image>
		    </view>
		</view>
		

		<!-- 发送数据区域 (注释掉的) -->
		<!-- <view class="send-section">
			<view class="section-title">控制区域</view>
			<view class="control-item" v-for="(item, index) in directives" :key="index">
				<button @click="sendDataToDevice(item.text)" class="control-btn-single">
					{{item.name}}
				</button>
				<view class="">{{item.id}}</view>
			</view>
		</view> -->
	</view> <!-- 正确的根容器结束标签 -->



</template>

<script>
	import {
		getUuid,
		setUuid,
		DEFAULT_UUID,
		getBluetoothConnection,
		setBluetoothConnection,
		removeBluetoothConnection
	} from '@/utils/bluetooth.js'
	import {
		directives
	} from '@/utils/directives';
	export default {
		data() {
			return {
				bluetooth: 1, //1：打开蓝牙  2：关闭蓝牙
				title: '蓝牙管理',
				searchLoadingTxt: '',
				isBlueOk: false,
				bluetimestoper: null,
				startchecktimer: null,
				timeoutOfBlueScanFailure30s: 300000,
				baseList: [],
				bluetoothIndex: [],
				targetDeviceName: '',
				_deviceId: '', //蓝牙deviceId
				pairedList: [], //已配对蓝牙
				pairedLists: [], //已配对蓝牙集合
				pairedHeight: 0, //已配对蓝牙显示高度
				unpairedList: [], //未配对蓝牙
				unpairedHeight: 0, //未配对蓝牙显示高度
				bluetoothSocket: null, //蓝牙socket连接
				sendData: '', //要发送的数据
				currentDevice: null, //当前连接的设备
				receiveData: '', // 存储接收到的数据
				inputStream: null, // 输入流对象
				isReceiving: false, // 是否正在接收数据
				uuid: DEFAULT_UUID, // 当前使用的UUID
				directives: directives, //指令
				switchStatus: 0,//按钮状态
				bluetoothMenu:false,//蓝牙连接状态
				
			}
		},
		onLoad() {
			// 检查并设置UUID
			this.checkAndSetUuid();
			//判断蓝牙打开状态
			this.bluetoothStatus();
			// 从缓存加载蓝牙连接信息
			const connection = getBluetoothConnection();
			console.log('缓存信息', connection);
			if (connection) {
				this.currentDevice = connection.device;
			}
		},
		beforeDestroy() {
			this.stopReceiving();
		},

		methods: {
			//打开蓝牙连接界面
			chooseBluetoothMenu(){
				this.bluetoothMenu= !this.bluetoothMenu
			},
			// 检查并设置UUID
			checkAndSetUuid() {
				const savedUuid = getUuid();
				if (!savedUuid) {
					this.promptForUuid();
				} else {
					this.uuid = savedUuid;
				}
			},

			// 提示用户输入UUID
			promptForUuid() {
				uni.showModal({
					title: '蓝牙UUID设置',
					content: '请输入蓝牙设备的UUID',
					editable: true,
					placeholderText: DEFAULT_UUID,
					confirmText: '确定',
					cancelText: '使用默认值',
					success: (res) => {
						let finalUuid = DEFAULT_UUID;
						if (res.confirm && res.content.trim()) {
							finalUuid = res.content.trim();
						}
						setUuid(finalUuid);
						this.uuid = finalUuid;
						uni.showToast({
							title: `UUID已设置为: ${finalUuid}`,
							icon: 'none'
						});
					}
				});
			},

			// 停止接收并释放蓝牙资源
			stopReceiving() {
				try {
					if (this.inputStream) {
						this.inputStream.close();
						this.inputStream = null;
					}
					if (this.bluetoothSocket) {
						this.bluetoothSocket.close();
						this.bluetoothSocket = null;
					}
					console.log("蓝牙资源已释放");
				} catch (e) {
					console.error("停止接收数据失败:", e);
				}
			},

			//关闭页面
			// close() {
			// 	uni.navigateBack();
			// },

			//删除已配对设备
			removePaire(index) {
				var that = this;
				uni.showModal({
					title: "提示",
					content: "是否删除设备",
					showCancel: true,
					cancelText: "取消",
					confirmText: "确定",
					success(res) {
						if (res.confirm) {
							var address = uni.getStorageSync("printerSelected").address;
							if (that.pairedList[index].address == address) {
								uni.setStorageSync("printerSelected", "");
								that.currentDevice = null;
							}
							for (var i = 0; i < that.pairedLists.length; i++) {
								if (that.pairedLists[i].getAddress() == that.pairedList[index].address) {
									that.pairedLists[i].removeBond();
								}
							}
							that.pairedList.splice(index, 1);
						}
					}
				})
			},

			//设置已选中蓝牙
			setSelectedPaired(paired) {
				var that = this;
				for (var i = 0; i < that.pairedList.length; i++) {
					if (that.pairedList[i].address == paired.address) {
						that.pairedList[i].isSelected = 1;
						that.connectToDevice(paired.address);
					} else {
						that.pairedList[i].isSelected = 0;
					}
				}
				uni.showToast({
					title: "已连接",
					icon: "success"
				})
				paired.isSelected = 1;
				uni.setStorageSync("printerSelected", paired);
			},

			//判断蓝牙打开状态
			bluetoothStatus() {
				var that = this;
				const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter');
				const blueadapter = BluetoothAdapter.getDefaultAdapter();

				if (blueadapter) {
					if (blueadapter.isEnabled()) {
						that.bluetooth = 0;
						var yilianjie = uni.getStorageSync("printerSelected");
						var selectAddress = "";
						if (yilianjie) {
							selectAddress = yilianjie.address;
							that.connectToDevice(selectAddress);
						}

						//获取手机已配对蓝牙
						var lists = blueadapter.getBondedDevices();
						plus.android.importClass(lists);
						var iterator = lists.iterator();
						plus.android.importClass(iterator);
						while (iterator.hasNext()) {
							var device = iterator.next();
							that.pairedLists.push(device);

							plus.android.importClass(device);
							that.pairedList.push({
								name: device.getName(),
								address: device.getAddress(),
								isSelected: selectAddress == device.getAddress() ? '1' : '0'
							})
						}
					} else {
						this.bluetooth = 1;
						this.pairedList = [];
						this.currentDevice = null;
					}
					this.unpairedList = [];
				}
			},

			//打开/关闭蓝牙
			toggleBluetooth() {
				if (this.bluetooth == 1) {
					this.openBluetooth();
				} else {
					this.closeBluetooth();
				}
			},

			//打开蓝牙
			openBluetooth() {
				var that = this;
				uni.showModal({
					title: "提示",
					content: "蓝牙尚未打开，是否打开蓝牙",
					showCancel: true,
					cancelText: "取消",
					confirmText: "确定",
					success(res) {
						if (res.confirm) {
							const BluetoothAdapter = plus.android.importClass(
								'android.bluetooth.BluetoothAdapter');
							const blueadapter = BluetoothAdapter.getDefaultAdapter();
							if (blueadapter != null) {
								that.bluetooth = 0;
								blueadapter.enable();

								setTimeout(function() {
									that.bluetoothStatus();
								}, 2000)
							}
						}
					}
				})
			},

			//关闭蓝牙
			closeBluetooth() {
				var that = this;
				uni.showModal({
					title: "提示",
					content: "蓝牙已打开，是否关闭蓝牙",
					showCancel: true,
					cancelText: "取消",
					confirmText: "确定",
					success(res) {
						if (res.confirm) {
							const BluetoothAdapter = plus.android.importClass(
								'android.bluetooth.BluetoothAdapter');
							const blueadapter = BluetoothAdapter.getDefaultAdapter();
							if (blueadapter != null) {
								that.bluetooth = 1;
								that.pairedList = [];
								that.unpairedList = [];
								that.currentDevice = null;
								that.receiveData = '';
								uni.setStorageSync("printerSelected", "");
								if (that.bluetoothSocket) {
									try {
										that.bluetoothSocket.close();
									} catch (e) {
										console.log("关闭socket错误:", e);
									}
									that.bluetoothSocket = null;
								}
								if (that.inputStream) {
									try {
										that.inputStream.close();
									} catch (e) {
										console.log("关闭输入流出错:", e);
									}
									that.inputStream = null;
								}
								blueadapter.disable();
							}
						}
					}
				})
			},

			//初始化蓝牙模块
			openBluetoothAdapter() {
				if (this.bluetooth == 1) {
					uni.showToast({
						title: "请先打开蓝牙",
						icon: "error"
					})
					return;
				}

				let system = uni.getSystemInfoSync();
				if (system.platform === 'android') {
					var that = this;
					var context = plus.android.importClass("android.content.Context");
					var locationManager = plus.android.importClass("android.location.LocationManager");
					var main = plus.android.runtimeMainActivity();
					var mainSvr = main.getSystemService(context.LOCATION_SERVICE);

					if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
						uni.showModal({
							title: "提示",
							content: "请打开定位服务功能",
							showCancel: false,
							success() {
								if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
									var Intent = plus.android.importClass('android.content.Intent');
									var Settings = plus.android.importClass('android.provider.Settings');
									var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
									main.startActivity(intent);
								}
							}
						});
						return false
					} else {
						that.searchDevices()
						return true
					}
				}
			},

			//搜索蓝牙
			searchDevices() {
				var that = this;
				that.unpairedList = [];

				uni.openBluetoothAdapter({
					success(res) {
						uni.getBluetoothAdapterState({
							success: function(res) {
								if (res.available) {
									uni.startBluetoothDevicesDiscovery({
										success(res) {
											var main = plus.android.runtimeMainActivity();
											var IntentFilter = plus.android.importClass(
												'android.content.IntentFilter');
											var BluetoothAdapter = plus.android.importClass(
												"android.bluetooth.BluetoothAdapter");
											var BluetoothDevice = plus.android.importClass(
												"android.bluetooth.BluetoothDevice");
											var BAdapter = BluetoothAdapter
												.getDefaultAdapter();

											uni.showLoading({
												title: "开始搜索设备",
											})

											var filter = new IntentFilter();
											var bdevice = new BluetoothDevice();
											BAdapter.startDiscovery();
											var receiver;
											receiver = plus.android.implements(
												'io.dcloud.android.content.BroadcastReceiver', {
													onReceive: function(context, intent) {
														plus.android.importClass(
															intent);
														if (intent.getAction() ==
															"android.bluetooth.adapter.action.DISCOVERY_FINISHED"
														) {
															main.unregisterReceiver(
																receiver);
															console.log("搜索结束");
															uni.hideLoading();
														} else {
															if (intent
																.getParcelableExtra(
																	BluetoothDevice
																	.EXTRA_DEVICE)
																.getBondState() === 10
															) {
																var y = 0;
																for (let x = 0; x <
																	that.unpairedList
																	.length; x++) {
																	if (that
																		.unpairedList[
																			x]
																		.address ==
																		intent
																		.getParcelableExtra(
																			BluetoothDevice
																			.EXTRA_DEVICE
																		)
																		.getAddress()
																	) {
																		y++;
																	}
																}
																if (y > 0) {
																	y = 0;
																} else {
																	that.unpairedList
																		.push({
																			name: intent
																				.getParcelableExtra(
																					BluetoothDevice
																					.EXTRA_DEVICE
																				)
																				.getName(),
																			address: intent
																				.getParcelableExtra(
																					BluetoothDevice
																					.EXTRA_DEVICE
																				)
																				.getAddress()
																		})
																}
															}
														}
													}
												});
											filter.addAction(bdevice.ACTION_FOUND);
											filter.addAction(BAdapter
												.ACTION_DISCOVERY_STARTED);
											filter.addAction(BAdapter
												.ACTION_DISCOVERY_FINISHED);
											filter.addAction(BAdapter.ACTION_STATE_CHANGED);
											main.registerReceiver(receiver, filter);
										}
									})
								}
							},
						})
					}
				})
			},

			//连接打印机
			createBLEConnection(mac_address) {
				if (!mac_address) {
					uni.showToast({
						title: "请选择蓝牙打印机",
						icon: "none"
					});
					return;
				}

				var main = plus.android.runtimeMainActivity();
				var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
				var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
				var UUID = plus.android.importClass("java.util.UUID");
				var BAdapter = BluetoothAdapter.getDefaultAdapter();
				var device = BAdapter.getRemoteDevice(mac_address);
				plus.android.importClass(device);
				var bdevice = new BluetoothDevice();
				var that = this;

				if (device.getBondState() == bdevice.BOND_NONE) {
					console.log("未配对蓝牙设备：" + device.getName() + '    ' + device.getAddress());
					if (mac_address == device.getAddress()) {
						if (device.createBond()) {
							console.log("配对成功")
							var cha = setInterval(function() {
								if (device.getBondState() == bdevice.BOND_BONDED) {
									clearInterval(cha);
									for (var i = 0; i < that.unpairedList.length; i++) {
										if (that.unpairedList[i].address == mac_address) {
											that.pairedList.push({
												name: that.unpairedList[i].name,
												address: that.unpairedList[i].address,
												isSelected: '0'
											});
											that.unpairedList.splice(i, 1);
											break;
										}
									}
									// 连接到设备
									that.connectToDevice(mac_address);
								}
							}, 1000)
						}
					}
				} else {
					// 连接到设备
					that.connectToDevice(mac_address);
				}
			},

			// 连接到设备
			connectToDevice(mac_address) {
				var that = this;
				// uni.showLoading({
				// 	title: '正在连接...'
				// });

				try {
					if (that.bluetoothSocket) {
						that.bluetoothSocket.close();
						that.bluetoothSocket = null;
					}
					if (that.inputStream) {
						that.inputStream.close();
						that.inputStream = null;
					}

					const BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
					const BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
					const UUID = plus.android.importClass("java.util.UUID");
					const BAdapter = BluetoothAdapter.getDefaultAdapter();
					const device = BAdapter.getRemoteDevice(mac_address);
					plus.android.importClass(device);

					// 使用缓存的UUID
					const uuid = UUID.fromString(this.uuid);

					const socket = device.createRfcommSocketToServiceRecord(uuid);
					plus.android.importClass(socket);

					new Promise((resolve, reject) => {
						try {
							socket.connect();
							resolve(socket);
						} catch (e) {
							reject(e);
						}
					}).then(socket => {
						that.bluetoothSocket = socket;
						that.currentDevice = device;

						// 缓存蓝牙连接信息
						setBluetoothConnection(socket, device);
						// uni.showToast({
						// 	title: '连接成功',
						// 	icon: 'success'
						// });
						uni.hideLoading();
						that.switchStatus = 1;
						console.log('按钮状态',this.switchStatus);
						for (var i = 0; i < that.pairedList.length; i++) {
							if (that.pairedList[i].address == mac_address) {
								that.pairedList[i].isSelected = 1;
								uni.setStorageSync("printerSelected", that.pairedList[i]);
							} else {
								that.pairedList[i].isSelected = 0;
							}
						}
					}).catch(e => {
						uni.hideLoading();
						uni.showToast({
							title: '连接失败: ' + e.message,
							icon: 'none'
						});
						console.error("连接失败:", e);
					});
				} catch (e) {
					uni.hideLoading();
					uni.showToast({
						title: '连接异常: ' + e.message,
						icon: 'none'
					});
					console.error("连接异常:", e);
				}
			},

			// 发送数据到设备
			sendDataToDevice(e) {
				console.log('使用的数据', e);
				const directives = e.split('').map(c => c.charCodeAt(0));;
				// console.log('数据',directives);
				// 优先使用当前连接的socket，如果没有则尝试从缓存获取
				let socket = this.bluetoothSocket;
				let device = this.currentDevice;

				if (!socket || !device) {
					const connection = getBluetoothConnection();
					if (connection) {
						device = connection.device;
						// 需要重新建立连接
						this.connectToDevice(device.address);
						return;
					}
				}

				if (!socket || !device) {
					uni.showToast({
						title: '请先连接蓝牙设备',
						icon: 'none'
					});
					return;
				}

				// if (!this.sendData || this.sendData.trim() === '') {
				// 	uni.showToast({
				// 		title: '请输入要发送的数据',
				// 		icon: 'none'
				// 	});
				// 	return;
				// }

				try {
					const OutputStream = plus.android.importClass("java.io.OutputStream");
					const os = socket.getOutputStream();
					plus.android.importClass(os);

					// 将字符串转换为字节数组
					const bytes = this.sendData.split('').map(c => c.charCodeAt(0));
					os.write(directives);
					os.flush();

					uni.showToast({
						title: '指令发送',
						icon: 'none'
					});
				} catch (e) {
					uni.showToast({
						title: '发送失败: ' + e.message,
						icon: 'none'
					});
					console.error("发送失败:", e);

					// 发送失败可能是连接已断开，清除缓存
					removeBluetoothConnection();
					this.bluetoothSocket = null;
					this.currentDevice = null;
				}
			},

		}
	}
</script>

<style>
	@import '@/static/css/index.css';

</style>